package flc.ast.activity;

import static flc.ast.utils.Content.BANK_CARD_REC;
import static flc.ast.utils.Content.BUSINESS_LICENSE_REC;
import static flc.ast.utils.Content.ID_CARD_REC;
import static flc.ast.utils.Content.identify_record_pic;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityRecCameraBinding;
import flc.ast.utils.Content;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class RecCameraActivity extends BaseAc<ActivityRecCameraBinding> {

    public static int type;
    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯
    private int idType;
    private boolean isSecond;//是否为第二张图片


    @Override
    protected int onCreate() {
        return R.layout.activity_rec_camera;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivCameraBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.ivCameraReversal.setOnClickListener(this);
        mDataBinding.ivCameraPicture.setOnClickListener(this);

        //身份证识别
        idType = getIntent().getIntExtra(Content.IdCardImg, 0);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCameraStart://开始拍摄
                if (mDataBinding.cameraView.isTakingPicture()) return;
                mDataBinding.cameraView.takePictureSnapshot();
                break;
            case R.id.ivCameraReversal://镜头反转
                reversalLens();
                break;
            case R.id.ivCameraFlash://闪光灯
                openFlash();
                break;
            case R.id.ivCameraPicture://相册选择
                if (type == 2) {
                    AlbumSelActivity.type = RecCameraActivity.type;
                    Intent intent = new Intent(mContext, AlbumSelActivity.class);
                    intent.putExtra(Content.IdCardImg, idType);
                    startActivityForResult(intent, ID_CARD_REC);
                } else if (type == 3) {
                    AlbumSelActivity.type = RecCameraActivity.type;
                    Intent intent = new Intent(mContext, AlbumSelActivity.class);
                    startActivityForResult(intent, BANK_CARD_REC);
                } else if (type == 4) {
                    AlbumSelActivity.type = RecCameraActivity.type;
                    Intent intent = new Intent(mContext, AlbumSelActivity.class);
                    startActivityForResult(intent, BUSINESS_LICENSE_REC);
                } else {
                    AlbumSelActivity.type = RecCameraActivity.type;
                    startActivity(AlbumSelActivity.class);
                }
                break;
        }
    }

    @Override
    protected void initData() {
        if (type == 0) {
            mDataBinding.tvCameraTitle.setText(getString(R.string.plant_rec));
        } else if (type == 1) {
            mDataBinding.tvCameraTitle.setText(getString(R.string.animal_rec));
        } else if (type == 2) {
            mDataBinding.tvCameraTitle.setText(getString(R.string.id_card_rec));
            mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.ashengfzzhenm);
        } else if (type == 3) {
            mDataBinding.tvCameraTitle.setText(getString(R.string.bank_rec));
            mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.ayinghangka);
        } else if (type == 4) {
            mDataBinding.tvCameraTitle.setText(getString(R.string.business_license_rec));
            mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.ayingyezhizhao);
        }
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                int width = result.getSize().getWidth();
                int height = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (width * height > screenWidth * screenHeight) {
                    width = screenWidth;
                    height = screenHeight;
                }
                result.toBitmap(width, height, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        startAct(bitmap);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    private void startAct(Bitmap bitmap) {

        if (type == 2 || type == 3 || type == 4) {
            bitmap = cropCurBmp(bitmap);
        }

        String filePath = FileUtil.generateFilePath(identify_record_pic, ".png");
        ImageUtils.save(bitmap, filePath, Bitmap.CompressFormat.PNG);

        if (type == 0 || type == 1) {
            IdentifyingActivity.imgPath1 = filePath;
            startActivity(IdentifyingActivity.class);
        } else if (type == 2) {
            if (!isSecond) {
                IdentifyingActivity.imgPath1 = filePath;
                mDataBinding.ivRecCameraIcon.setImageResource(R.drawable.ashengfenzbeim);
                isSecond = true;
            } else {
                IdentifyingActivity.imgPath2 = filePath;
                Intent intent = new Intent(mContext, IdentifyingActivity.class);
                intent.putExtra(Content.IdCardImg, idType);
                intent.putExtra(Content.IsCamera, "IsCamera");
                startActivityForResult(intent, ID_CARD_REC);
            }
        } else if (type == 3) {
            IdentifyingActivity.imgPath1 = filePath;
            Intent intent = new Intent(mContext, IdentifyingActivity.class);
            startActivityForResult(intent, BANK_CARD_REC);
        } else if (type == 4) {
            IdentifyingActivity.imgPath1 = filePath;
            Intent intent = new Intent(mContext, IdentifyingActivity.class);
            startActivityForResult(intent, BUSINESS_LICENSE_REC);
        }

    }

    private Bitmap cropCurBmp(Bitmap mCurBmp) {
        int[] olForRefer = new int[2];
        int[] olForPic = new int[2];
        mDataBinding.ivRecCameraIcon.getLocationInWindow(olForRefer);
        mDataBinding.cameraView.getLocationInWindow(olForPic);
        int x = olForRefer[0] - olForPic[0];
        x = (int) (mCurBmp.getWidth() * (x * 1f / mDataBinding.cameraView.getWidth()));

        int y = olForRefer[1] - olForPic[1];
        y = (int) (mCurBmp.getHeight() * (y * 1f / mDataBinding.cameraView.getHeight()));

        int width = (int) (mCurBmp.getWidth() * (mDataBinding.ivRecCameraIcon.getWidth() * 1f / mDataBinding.cameraView.getWidth()));
        if (x + width > mCurBmp.getWidth()) {
            width = mCurBmp.getWidth() - x;
        }
        int height = (int) (mCurBmp.getHeight() * (mDataBinding.ivRecCameraIcon.getHeight() * 1f / mDataBinding.cameraView.getHeight()));
        if (y + height > mCurBmp.getHeight()) {
            height = mCurBmp.getHeight() - y;
        }
        return ImageUtils.clip(mCurBmp, x, y, width, height, true);
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.ashoudiantguan);
            mDataBinding.tvCameraFlash.setText(getString(R.string.flash_close));
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.ashoudiantkai);
            mDataBinding.tvCameraFlash.setText(getString(R.string.flash_open));
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
            mDataBinding.ivCameraReversal.setImageResource(R.drawable.ayifanzhuan);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
            mDataBinding.ivCameraReversal.setImageResource(R.drawable.afanzhuanxiangji);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == ID_CARD_REC || requestCode == BANK_CARD_REC || requestCode == BUSINESS_LICENSE_REC) {
                Intent intent = new Intent();
                setResult(RESULT_OK, data);
                finish();
            }
        }
    }


}